package com.softwinner.awbt.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Service;
import android.content.Intent;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteCallbackList;

import com.goodocom.gocsdk.IGocsdkCallback;
import com.goodocom.gocsdk.SerialPort;
import com.softwinner.awbt.common.Commands;
import com.softwinner.awbt.common.Config;
import com.softwinner.awbt.utils.LOG;


public class GocsdkService extends Service {
    public static final String TAG = "GocsdkService";
    public static final int MSG_START_SERIAL = 1;// 串口
    public static final int MSG_SERIAL_RECEIVED = 2; // 接收到串口信息
    private static final int RESTART_DELAY = 2000; // ms
    // 命令解析
    private CommandParser mCommandParser;
    // 是否使用socket
    private final boolean isUseSocket = false;
    // 串口线程
    private SerialThread mSerialThread = null;
    private volatile boolean isRunning = true;
    private RemoteCallbackList<IGocsdkCallback> mCallbacks;

    public static boolean isBehind = false;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(android.os.Message msg) {
            LOG.i(TAG + "--->handleMessage  MSG = " + msg.what);
            if (msg.what == MSG_START_SERIAL) {
                mSerialThread = new SerialThread();
                mSerialThread.start();
            } else if (msg.what == MSG_SERIAL_RECEIVED) {
                byte[] data = (byte[]) msg.obj;
                LOG.i("handleMessage  data = " + data);
                mCommandParser.onBytes(data);
            }
        }
    };

    @Override
    public void onCreate() {
        LOG.i(TAG + "--->Service+onCreate()");
        mCallbacks = new RemoteCallbackList<IGocsdkCallback>();
        mCommandParser = new CommandParser(mCallbacks, this);
        mHandler.sendEmptyMessage(MSG_START_SERIAL);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LOG.i(TAG + "--->服务启动了+onStartCommand");
        isBehind = true;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        LOG.e(TAG + "--->Service+onDestroy");
        isRunning = false;
        mCallbacks.kill();
        write(Commands.STOP_MUSIC);
        super.onDestroy();
    }


    @Override
    public IBinder onBind(Intent intent) {
        LOG.i(TAG + "--->服务绑定了+onBind");
        isBehind = false;
        return new GocsdkServiceImp(this);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        isBehind = true;
        LOG.i(TAG + "--->服务解绑了+onUnbind");

        return super.onUnbind(intent);
    }

    class SerialThread extends Thread {
        private InputStream inputStream;
        private OutputStream outputStream = null;
        private byte[] buffer = new byte[1024];

        public void write(byte[] buf) {
            if (outputStream != null) {
                try {
                    outputStream.write(buf);
                } catch (IOException e) {

                }
            }
        }

        public SerialThread() {
        }

        @Override
        public void run() {
            LOG.i(TAG + "--->-SerialThread---run");
            LocalSocket client = null;
            SerialPort serial = null;

            int n;
            try {
                if (isUseSocket) {
                    client = new LocalSocket();
                    client.connect(new LocalSocketAddress(Config.SERIAL_SOCKET_NAME,
                            LocalSocketAddress.Namespace.RESERVED));
                    inputStream = client.getInputStream();
                    outputStream = client.getOutputStream();
                } else {
                    serial = new SerialPort(new File("/dev/goc_serial"), 115200, 0);
                    inputStream = serial.getInputStream();
                    outputStream = serial.getOutputStream();
                }
                while (isRunning) {
                    n = inputStream.read(buffer);
                    if (n < 0) {
                        if (isUseSocket) {
                            if (client != null) client.close();
                        } else {
                            if (serial != null) serial.close();
                        }
                        throw new IOException("n==-1");
                    }

                    byte[] data = new byte[n];
                    System.arraycopy(buffer, 0, data, 0, n);
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SERIAL_RECEIVED, data));
                }
            } catch (IOException e) {
                try {
                    if (isUseSocket) {
                        if (client != null) client.close();
                    } else {
                        if (serial != null) serial.close();
                    }
                } catch (IOException e1) {
                    // e1.printStackTrace();
                }
                mHandler.sendEmptyMessageDelayed(MSG_START_SERIAL, RESTART_DELAY);
                return;
            }

            try {
                if (isUseSocket) {
                    if (client != null) client.close();
                } else {
                    if (serial != null) serial.close();
                }
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
    }

    public void write(String str) {
        if (mSerialThread == null) return;
        mSerialThread.write((Commands.COMMAND_HEAD + str + "\r\n").getBytes());
    }

    public void registerCallback(IGocsdkCallback callback) {
        mCallbacks.register(callback);
    }

    public void unregisterCallback(IGocsdkCallback callback) {
        mCallbacks.unregister(callback);
    }

}
